package com.util;

import com.dao.BookMapper;
import com.dao.UserMapper;
import com.model.Book;
import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 汪林
 * @date 2020/8/5 12:45
 */
@Component
public class EmailSendUtil {
    //注入第三方组件
    @Autowired
    private JavaMailSender mail;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BookMapper bookMapper;
    //注册时间
    private String registerTime;

    //还书通知
    public void sendMessage(Integer userId,Integer bookId) {
        //通过id动态获得用户表里面的收件人邮箱、姓名
        User user = userMapper.selectByPrimaryKey(userId);
        String receiverEamil = user.getEmail();
        String receiverName = user.getUsername();
        //获得书籍名称
        Book book = bookMapper.selectByPrimaryKey(bookId);
        String bookName = book.getBookName();
        //创建邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //定义发件人
        simpleMailMessage.setFrom("3342655315@qq.com");
        //定义收件人
        simpleMailMessage.setTo(receiverEamil);
        //定义主题
        simpleMailMessage.setSubject("3组图书馆");
        //定义正文
        simpleMailMessage.setText("尊敬的"+receiverName+"先生，您借阅的书籍《"+bookName+"》的日期即将到期，请尽快还书！");
        try{
            mail.send(simpleMailMessage);
            System.out.println("发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败");
        }
    }

    //注册
    public void sendMessage(User user) {
        //获取当前注册时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        registerTime=sdf.format(new Date());

        //注册用户姓名
        String registerName = user.getUsername();
        //获得用户邮箱
        String registerEmail = user.getEmail();

        //创建邮件
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        //定义发件人
        simpleMailMessage.setFrom("3342655315@qq.com");
        //定义收件人
        simpleMailMessage.setTo(registerEmail);
        //定义主题
        simpleMailMessage.setSubject("虎虎图书馆");
        simpleMailMessage.setText("尊敬的"+user.getUsername()+"先生，您于"+registerTime+"注册虎虎图书馆帐号,点击以下链接，即可激活该帐号" +
                "http://192.168.18.170:8080/bookmanagement_war_exploded/register/ActiveUser.do?registerEmail="+registerEmail);
        try{
            mail.send(simpleMailMessage);
            System.out.println("发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败");
        }
    }
}

